package com.bootx.controller.api;

import com.bootx.entity.WriteTool;
import com.bootx.entity.WriteToolCategory;
import com.bootx.entity.WriteToolTask;
import com.bootx.pojo.MyChatMessage;
import com.bootx.pojo.Demo;
import com.bootx.pojo.FormItem;
import com.bootx.service.WriteToolCategoryService;
import com.bootx.service.WriteToolService;
import com.bootx.service.WriteToolTaskService;
import com.bootx.util.AiXieZuoYuUtils;
import com.bootx.util.JsonUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import dev.langchain4j.data.message.SystemMessage;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.StreamingChatModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.chat.response.StreamingChatResponseHandler;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/api")
public class WriteController {

    @Resource(name = "openAiStreamingChatModel1")
    private StreamingChatModel streamingChatModel;

    @Resource
    private WriteToolCategoryService writeToolCategoryService;
    @Resource
    private WriteToolService writeToolService;

    @Resource
    private WriteToolTaskService writeToolTaskService;

    @PostMapping(value = "/write")
    public Flux<MyChatMessage> chat(String taskId, HttpServletResponse response){

        WriteToolTask writeToolTask = writeToolTaskService.findBySn(taskId);
        if(writeToolTask == null){
            return Flux.empty();
        }
        Integer userInputType = writeToolTask.getUserInputType();
        WriteTool writeTool = writeToolTask.getWriteTool();
        String userPrompt = writeTool.getUserPrompt();
        if(userInputType == 1){
            // json格式
            Map<String,String> map = JsonUtils.toObject(writeToolTask.getContent(),new TypeReference<Map<String,String>>(){});
            Set<String> keySet = map.keySet();
            for (String key : keySet) {
                userPrompt = userPrompt.replace("["+key+"]",map.get(key));
            }
        }else{
            userPrompt = writeToolTask.getContent();
        }

        String messageId = UUID.randomUUID().toString();
        response.setContentType(MediaType.TEXT_EVENT_STREAM_VALUE+";charset=UTF-8");
        String finalUserPrompt = userPrompt;
        return Flux.create((sink ) -> {
            streamingChatModel.chat(List.of(
                    SystemMessage.from(writeTool.getSystemPrompt()),
                    UserMessage.from(finalUserPrompt)
            ), new StreamingChatResponseHandler() {
                @Override
                public void onPartialResponse(String partialResponse) {
                    System.out.print(partialResponse);
                    sink.next(MyChatMessage.userMessage(partialResponse,messageId));
                }

                @Override
                public void onCompleteResponse(ChatResponse completeResponse) {
                    System.out.println("\n--- 完成 ---");
                    String text = completeResponse.aiMessage().text();
                    writeToolTask.setResult(text);
                    writeToolTask.setStatus(2);
                    writeToolTaskService.update(writeToolTask);
                    sink.complete();
                }

                @Override
                public void onError(Throwable error) {
                    error.printStackTrace();
                }
            });
        });
    }


    @PostMapping(value = "/init")
    public String init(String content){
        List<Demo.ChildrenBean> list = JsonUtils.toObject(content, new TypeReference<List<Demo.ChildrenBean>>() {
        });
        // 先保存分类
        list.forEach(demo -> {
            WriteTool writeTool = new WriteTool();
            writeTool.setMemo(demo.getIntroduce());
            writeTool.setName(demo.getTitle());
            writeTool.setIcon(demo.getIcon());
            writeTool.setPath(demo.getPath());
            if(StringUtils.isEmpty(writeTool.getIcon())){
                writeTool.setIcon(demo.getImg());
            }
            writeTool = writeToolService.create(writeTool,null);
        });
        return "";
    }

    @GetMapping(value = "/init1")
    public String init1(){
        List<WriteTool> all = writeToolService.findAll();
        all.forEach(writeTool -> {
            try {
                List<FormItem> formItems = AiXieZuoYuUtils.getFormItems("https://www.aixiezuoyu.com"+writeTool.getPath());
                writeTool.setFormItems(formItems);
                writeToolService.update(writeTool);
            } catch (IOException e) {

            }
        });


        return "";
    }

    @PostMapping(value = "/create")
    public String create(Long categoryId,String[] names){
        WriteToolCategory writeToolCategory = writeToolCategoryService.find(categoryId);
        Arrays.stream(names).forEach(item->{
            WriteTool writeTool = new WriteTool();
            writeTool.setName(item);
            writeToolService.create(writeTool,writeToolCategory);
        });
        return "";
    }
}
